package modbus_master_connector

import (
	"go-iot-gateway/internal/apk/maths"
	conf_table_define "go-iot-gateway/internal/conf_table/define"
	"go-iot-gateway/pkg/modbus"
	"strconv"
	"time"
)

type ModbusTCPConnector struct {
	abstractModbusConnector
	tcpClientHandler *modbus.TCPClientHandler
	protocolInfo     *TCPProtocolInfo
}

func (m *ModbusTCPConnector) _init(protocolConfInfos []*conf_table_define.ProtocolInfo) {
	m.protocolInfo = NewTCPProtocolInfo(protocolConfInfos)
	m.tcpClientHandler = modbus.NewTCPClientHandler(m.ChannelInfo.ConnectParams.IpAddr + ":" + strconv.Itoa(int(m.ChannelInfo.ConnectParams.Port)))
	m.tcpClientHandler.Timeout = time.Duration(m.ChannelInfo.ConnectParams.Timeout) * time.Millisecond
	m.tcpClientHandler.Logger = m.logger

	idleTime := maths.MaxInt(m.ChannelInfo.Frequency, m.ChannelInfo.ConnectParams.Timeout)
	m.tcpClientHandler.IdleTimeout = time.Duration(idleTime+7000) * time.Millisecond
	//读取数据
	m.modbusClient = modbus.NewClient(m.tcpClientHandler)
}

func (m *ModbusTCPConnector) _connect() error {
	return m.tcpClientHandler.Connect()
}

func (m *ModbusTCPConnector) _close() {
	err := m.tcpClientHandler.Close()
	if err != nil {
		m.logger.Info(err)
	}
}

func (m *ModbusTCPConnector) _numOfRegisterPerFrame() uint16 {
	return m.protocolInfo.NumOfRegisterPerFrame
}

// tcp 连接 , rtu 协议
type ModbusTCPRTUConnector struct {
	abstractModbusConnector
	tcpClientHandler *modbus.TCPRTUClientHandler
	protocolInfo     *TCPProtocolInfo
}

func (m *ModbusTCPRTUConnector) _init(protocolConfInfos []*conf_table_define.ProtocolInfo) {
	m.protocolInfo = NewTCPProtocolInfo(protocolConfInfos)
	m.tcpClientHandler = modbus.NewTCPRTUClientHandler(m.ChannelInfo.ConnectParams.IpAddr + ":" + strconv.Itoa(int(m.ChannelInfo.ConnectParams.Port)))
	m.tcpClientHandler.Timeout = time.Duration(m.ChannelInfo.ConnectParams.Timeout) * time.Millisecond
	m.tcpClientHandler.Logger = m.logger
	//m.tcpClientHandler.IdleTimeout = 60 * time.Second

	//读取数据
	m.modbusClient = modbus.NewClient(m.tcpClientHandler)
}

func (m *ModbusTCPRTUConnector) _connect() error {
	return m.tcpClientHandler.Connect()
}

func (m *ModbusTCPRTUConnector) _close() {
	err := m.tcpClientHandler.Close()
	if err != nil {
		m.logger.Info(err)
	}
}

func (m *ModbusTCPRTUConnector) _numOfRegisterPerFrame() uint16 {
	return m.protocolInfo.NumOfRegisterPerFrame
}

func (m *ModbusTCPConnector) _sendLock() {
	//tpc 不需要加锁处理
}
func (m *ModbusTCPConnector) _sendUnLock() {
	//tpc 不需要加锁处理
}

func (m *ModbusTCPConnector) _writeRetryOnFail() uint8 {
	//todo _writeRetryOnFail
	return 1
}
